package com.zhx.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * session失效的时候的监听器
 * @author: zhx
 * @create: 2021-03-21 21:58
 **/
public class SessionFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        String requestURI = request.getRequestURI();
        String uri = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        HttpSession session = request.getSession(false);//传入false，如果没有session，就返回null
        ServletContext application = request.getServletContext();
        String session1 = (String) application.getAttribute("session1");
        if(session1==null||session1.equals("1")){
            application.setAttribute("session1", session.getId());
        }
        session1= (String) application.getAttribute("session1");
        if (session==null||!session.getId().equals(session1)){
            application.setAttribute("session1","1" );
            response.sendRedirect(request.getContextPath()+"/Login.html");
            return;
        }else{
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
